#include<iostream>
using namespace std;

//Definition for singly - linked list.
struct ListNode {
	int val;
	ListNode* next;
	ListNode() : val(0), next(nullptr) {}
	ListNode(int x) : val(x), next(nullptr) {}
	ListNode(int x, ListNode* next) : val(x), next(next) {}

};

ListNode* removeNthFromEnd(ListNode* head, int n) {
	ListNode* dummyHead = new ListNode(0);
	dummyHead->next = head;//creat a dummyhead
	ListNode* fast = dummyHead;//end on NULL
	ListNode* slow = dummyHead;//end on before
	
	for (; n >= 0 && fast != NULL; n--) {
		fast = fast->next;
	}//move fast n+1 times

	/*while (n-- && NULL != fast) {
		fast = fast->next;
	}
	fast = fast->next;*/

	while (NULL != fast) {
		fast = fast->next;
		slow = slow->next;
	}//move slow to before when fast equal to NULL

	slow->next = slow->next->next;//connect to next or delete target
	return dummyHead->next;//return the real head
}